import vue from '@vitejs/plugin-vue'

import AutoImport from "unplugin-auto-import/vite"
import Components from 'unplugin-vue-components/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';

import postcss from 'postcss';
import pxtorem from 'postcss-pxtorem';

import { UserConfigExport, ConfigEnv, loadEnv } from 'vite';

import { resolve } from 'path';
import WindiCSS from 'vite-plugin-windicss';


export default ({mode}: ConfigEnv): UserConfigExport => {
  const root = process.cwd();
  const env = loadEnv(mode, root);

  return {
    base: './',
    build: {
      chunkSizeWarningLimit: 1500,
      emptyOutDir: true,
      outDir: env.VITE_OUTPUTDIR || 'build',
      rollupOptions: {
        output:{
          manualChunks(id) {
            if (id.includes('node_modules')) {
                return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
          // 用于从入口点创建的块的打包输出格式[name]表示文件名,[hash]表示该文件内容hash值
          entryFileNames: 'static/js/[name]-[hash].js',
          // 用于命名代码拆分时创建的共享块的输出命名
          chunkFileNames: 'static/js/[name]-[hash].js',
          // 用于输出静态资源的命名，[ext]表示文件扩展名
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
    },
    plugins: [
      vue(),
      WindiCSS(),
      // 自动引入相关API
      AutoImport ({
        imports: ["vue", "vue-router", "pinia"], // 自动导入vue和vue-router,pinia,vueuse相关函数
        dts: "types/auto-import.d.ts", // 生成 `auto-import.d.ts` 全局声明
        eslintrc: {
          enabled: true
        },
        resolvers: []
      }),
      // 自动引入组件
      Components({
        dts: 'types/components.d.ts',
        dirs: ['src/components'],
        resolvers: [NaiveUiResolver()]
      })
    ],

    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/mixin.scss";'
        }
      }
    },
    json: {
      // see https://cn.vitejs.dev/config/shared-options.html#json-stringify
      stringify: true
    },
    // 自动打开页面
    preview: {
      open: true
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, './src')
      }
    },

    server: {
      host: true,
      open: true,
      port: 8088,
      proxy: {
        '/api/v1': {
          target: env.VITE_API_URL,
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(new RegExp(`^/api/v1`), ''),
        },
        '/upload': {
          target: env.VITE_UPLOAD_URL,
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(new RegExp(`^/upload`), ''),
        },
        '/media': {
          target: env.VITE_MEDIA_URL,
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(new RegExp(`^/media`), ''),
        },
        '/weather': {
          target: 'http://vaw.tongliao.sugonup.com',
          changeOrigin: true
        },
      }
    }
  }
}